<?php


namespace App\Middleware;


use App\Kernel\Http\Response;
use App\Kernel\Util\JwtInstance;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AdminMiddleware implements MiddlewareInterface
{
    protected $container;
    /**
     * @Inject()
     * @var Response
     */
    private $response;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
//        $request = $this->container->get(RequestInterface::class);
        $token = $request->getHeaderLine('Authorization');
        if(empty($token)) {
            $token = $request->query('token');
        }
////        $uri = $request->getRequestUri();
////        $urIs = explode('/', $uri);
////
////        $perms = null;
////
////        $perms = null;
////        if (count($urIs) >= 5) { // 权限标识
////            $perms = $urIs[2] . ":" . $urIs[3] . ":" . $urIs[4];
////        }
//
        if (empty($token)) {
            return $this->response->error("token not null");
        }
////        return $handler->handle($request);
        try {
            JwtInstance::instance()->decode($token);
            return $handler->handle($request);
        } catch (\Throwable $e) {
            return $this->response->error($e->getMessage());
        }

//        $allowPermissions = [];

//        if ($accessUserId != 1) {
//
//            [$menuList, $permissions] = $this->sysUserService->getNemuNav($accessUserId);
//
//            if (!empty($perms)) {
//                // 没有访问权限
//                if (!in_array($perms, $allowPermissions) && !in_array($perms, $permissions)) {
//                    return $this->respone->error('PERMISSION_DENIED');
//                }
//            }
//        }
        return $handler->handle($request);

//        try {
//            JwtInstance::instance()->build()->getId();
//            return $handler->handle($request);
//        } catch (\Exception $e) {
//            return $this->response->error($e->getMessage());
//        }


    }


}